<?php

/**
 * 算术验证码
 */
namespace lico\Tool\Captcha;

use lico\Tool\Helper;

class Arithmetic
{

    protected $code;
    protected $data;
    protected $config;
    protected $operatorArr = ['+', '-', 'x', '÷'];

    public function __construct($config)
    {
        $this->config = $config;
    }

    /**
     * 获取运算符
     */
    public function getOperator()
    {
        $index = mt_rand(0, 3);
        $operator = $this->operatorArr[$index];
        return $operator;
    }

    /**
     * 验证码
     */
    protected function getRandStr($length)
    {
        //p($length);
        $realLength = $length < 4 ? 2 : (int) $length - 2;
        $operator = $this->getOperator(); //p($operator,$realLength);

        $maxIndex = $realLength > 2 ? 2 : 1; //最大幂
        $dividend = mt_rand(1, (10 ^ $maxIndex) - 1); //p($dividend);
        $dividendLen = strlen($dividend); //p($dividendLen);
        $divisorLen = $realLength - $dividendLen; //p($divisorLen);
        $divisor = $divisorLen ? mt_rand(0, (10 ^ $divisorLen) - 1) : 0;

        switch ($operator) {
            case '+':
                $this->data = $divisor + $dividend;
                break;
            case '-':
                $this->data = $divisor - $dividend;
                break;
            case 'x':
                $this->data = $divisor * $dividend;
                break;
            case '÷':
                for ($index = $divisorLen; $index >= 0; $index--) {
                    $divisor = $dividend * $index;
                    if (strlen($divisor) <= $divisorLen) {
                        break;
                    }
                }
                $divisor = $divisor ?: 0;
                $this->data = $divisor / $dividend;
                break;
            default:
                break;
        }
        // p($divisor,$dividend);
        return $divisor . $operator . $dividend . '=';
    }

    /**
     * 验证码
     */
    public function getCode($length = '')
    {
        if (is_null($this->code) && $length) {
            $this->code = $this->getRandStr($length);
        }
        return $this->code;
    }

    /**
     * 干扰点
     */
    public function getSpot($length)
    {

        $operatorNum = intval($length / 4);
        $operators = '';
        for ($index = 0; $index < $operatorNum; $index++) {
            $operators .= $this->getOperator() . '=';
        }

        $numLen = $length - 2 * $operatorNum;
        $num = Helper::getRandStr($numLen, 'number');
        $str = $operators . $num;
        return str_shuffle($str);
    }

    /**
     * 获取校验值
     */
    public function getData()
    {
        return $this->data;
    }
}
